import serial
import datetime
import os
import time

# 设定串口参数
ser = serial.Serial('/dev/ttyAMA5', 9600, timeout=1)

# 设定设备名
device_name = "R1000 NO.1"

# 设定日志文件夹路径
log_folder = "log"
if not os.path.exists(log_folder):
    os.makedirs(log_folder)

# 设定日志文件名
log_file_name = "rs232.log"
log_file_path = os.path.join(log_folder, log_file_name)

try:
    while True:
        # 获取当前时间
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 发送设备名
        ser.write(device_name.encode())
        print("{} - Sending device name: {}".format(current_time, device_name))
        
        # 将发送的时间写入日志文件
        with open(log_file_path, "a") as log_file:
            log_file.write(f"{current_time} - Sending device name: {device_name}\n")
        
        # 等待接收数据，如果1秒内没有数据则认为超时
        start_time = datetime.datetime.now()
        data = ""
        while (datetime.datetime.now() - start_time).seconds < 1 and ser.in_waiting == 0:
            pass  # 等待数据到达
        
        if ser.in_waiting > 0:
            data = ser.readline().decode().strip()
            # 获取当前时间
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            # 将接收到的数据和时间写入日志文件
            with open(log_file_path, "a") as log_file:
                log_file.write(f"{current_time} - Received: {data}\n")
            print("{} - Received: {}".format(current_time, data))
        else:
            # 获取当前时间
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            # 将接收失败的信息写入日志文件
            with open(log_file_path, "a") as log_file:
                log_file.write(f"{current_time} - Receive failed\n")
            print("{} - Receive failed".format(current_time))
        
        # 每次循环后等待秒
        time.sleep(0.5)
except KeyboardInterrupt:
    print("\nProgram stopped by user.")
finally:
    ser.close()
    print("Serial port closed.")
